/**
 * This file is part of git-as-svn. It is subject to the license terms
 * in the LICENSE file found in the top-level directory of this distribution
 * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
 * including this file, may be copied, modified, propagated, or distributed
 * except according to the terms contained in the LICENSE file.
 */
package svnserver.server;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tmatesoft.svn.core.SVNException;
import svnserver.service.Parameters;
import svnserver.service.Resque;

import java.io.*;

/**
 * Entry point.
 *
 * @author a.navrotskiy
 */
public class Main {
    @NotNull
    private static final Logger log = LoggerFactory.getLogger(SvnServer.class);

    private static boolean ParametersInitialize() {
        try {
            java.net.URL url = Main.class.getProtectionDomain().getCodeSource().getLocation();
            String path = java.net.URLDecoder.decode(url.getPath(), "utf-8");
            if (path.endsWith(".jar")) {
                path = path.substring(0, path.lastIndexOf('/') + 1) + "/sserver.toml";
            } else {
                path = "./sserver.toml";
            }
            return Parameters.Initialize(path);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return false;
    }

    public static void main(@NotNull String[] args) throws IOException, SVNException, InterruptedException {
        log.info("SServer.Subversion.Bridge.Middleware: 1.7");
        final CmdArgs cmd = new CmdArgs();
        final JCommander jc = new JCommander(cmd);
        jc.parse(args);
        if (cmd.help) {
            jc.usage();
            return;
        }
        if (!ParametersInitialize()) {
            log.error("load sserver.toml failed");
            return;
        }
        if (!Resque.RedissonInitialize(Parameters.Get().RedisHost())) {
            log.info("Initialize redis client: {}", Parameters.Get().RedisHost());
            return;
        }
        final SvnServer server = new SvnServer();
        server.start();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                server.shutdown(Parameters.Get().Shuttime());
                Resque.getRedisson().shutdown();
            } catch (IOException | InterruptedException e) {
                log.error("Can't shutdown correctly", e);
            }
        }));
        server.join();
    }

    public static class CmdArgs {
        @Parameter(names = { "-h", "--help" }, description = "Show help", help = true)
        private boolean help = false;
    }

}
